<?php

namespace app\models\group;

use app\models\order\Order;
use app\models\product\Product;
use app\models\user\User;
use app\models\user\UserCommission;
use Yii;

/**
 * This is the model class for table "group".
 *
 * @property int $id
 * @property int $user_id 发起者
 * @property int $product_id
 * @property string $create_time
 * @property string $update_time
 * @property int $status 状态 1正在进行中, 0未支付 (进行中的必须是支付过的), 2 完成
 * @property int $order_id 订单ID
 * @property int $is_random 是否为随机团
 */
class Group extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'group';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['user_id', 'product_id', 'status', 'order_id'], 'integer'],
            [['product_id'], 'required'],
            [['create_time', 'update_time'], 'safe'],

            [['is_random'], 'safe']
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'user_id' => 'User ID',
            'product_id' => 'Product ID',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
            'status' => 'Status',
            'order_id' => 'Order ID',
        ];
    }

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            $time = date('Y-m-d H:i:s');
            $this->update_time = $time;
            if ($insert) {
                $this->create_time = $time;
            }
            return true;
        }
        return false;
    }

    public function getOrder()
    {
        return $this->hasOne(Order::class, ['id' => 'order_id']);
    }

    public function getProduct()
    {
        return $this->hasOne(Product::class, ['id' => 'product_id']);
    }

    public function getFans()
    {
        return $this->hasMany(GroupFans::class, ['group_id' => 'id'])
            ->where(['status' => 1]);
    }

    public function getUser()
    {
        return $this->hasOne(User::class, ['id' => 'user_id'])
            ->select(['id', 'mobile', 'nickname', 'level', 'group_level', 'avatar']);
    }

    public function getCommission()
    {
        return $this->hasMany(UserCommission::class, ['group_order_id' => 'id']);
    }
}
